package com.example.demo.service;

import com.example.demo.domain.User;
import com.example.demo.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.Optional;
import java.util.concurrent.TimeUnit;

//业务类
@Service
@Transactional//添加事务注解，否则缓存更新出错
public class UserService {

    @Autowired
    private UserMapper userMapper;

    /**
     * 根据id查询
     */
    //@Cacheable(cacheNames = "comment")//存放在名为comment的默认缓存中

    @Autowired
    private RedisTemplate redisTemplate;//通过api操纵redis

    //查询
    public User findById(Integer id){
        Object o=redisTemplate.opsForValue().get("user_"+id);//得到缓存
        if(o!=null){
            //缓存中有数据
            System.out.println("来自缓存");
            return (User) o;
        }
        else {
            User user=userMapper.selectUser(id);
            //如果缓存中没有数据，存进缓存中,缓存时间为1 ，天
            redisTemplate.opsForValue().set("user_"+id,user,1, TimeUnit.DAYS);
            return  user;
            
        }
    }
    
}
